<script lang="ts">
//返回顶部组件
import { defineComponent, onMounted, ref } from "vue";
import { debounce } from "../../libs/index";

export default defineComponent({
  name: "BackTop",
  props: {
    bgColor: {
      type: String,
      default: "#0fa3fa",
    },
  },
  setup(props) {
    const animation = ref<String>("btn-noshow");

    const show = ref<Boolean>(false);

    const handleBackTop = () => {
      if (show.value) {
        let scrollTop =
          window.pageYOffset ||
          document.documentElement.scrollTop ||
          document.body.scrollTop;
        if (scrollTop > 0) {
          window.requestAnimationFrame(handleBackTop); //相当于计时器方式
          window.scrollTo(0, scrollTop - scrollTop / 10);
        }
      }
    };

    onMounted(() => {
      window.addEventListener("scroll", windowScroll);
    });

    const windowScroll = () => {
      debounce(() => {
        let scrollTop =
          window.pageYOffset ||
          document.documentElement.scrollTop ||
          document.body.scrollTop;
        if (scrollTop > 0) {
          show.value = true;
          animation.value = "btn-fadein";
        } else {
          animation.value = "btn-fadeout";

          show.value = false;
        }
      },100);
    };

    return { handleBackTop, props, animation };
  },
});
</script>

<template>
  <div
    :class="['backTop', animation]"
    :style="{ background: props.bgColor }"
    @click="handleBackTop"
  >
    <span class="icondemo demo-huidingbu top-icon"></span>
  </div>
</template>

<style lang="scss" scoped>
.backTop {
  width: 40px;
  height: 40px;
  position: fixed;
  bottom: 40px;
  right: 20px;
  border-radius: 100%;
  overflow: hidden;
  text-align: center;
  line-height: 40px;
  border: 1px solid #fafafa;
  .top-icon {
    color: #fff;
    font-size: 18px;
    font-weight: bold;
  }
}
.btn-noshow {
  opacity: 0;
}
.btn-fadein {
  animation: btn-fadein 0.5s ease-in 1;
  opacity: 1;
}

.btn-fadeout {
  animation: btn-fadeout 0.5s ease-in 1;
  opacity: 0;
}

/* 淡入 */
@keyframes btn-fadein {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

/* 淡出 */
@keyframes btn-fadeout {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}
</style>
